const multer = require('multer');
const AdmZip = require('adm-zip');
const path = require('path');
const fs = require('fs-extra');
const { cloundPath } = require('../config/config');
const categorizeFiles = require('../utils/fileClassify')
const mammoth = require("mammoth");

// 配置 Multer
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    console.log("🚀 ~ req:", req.body)
    cb(null, getFilePath(req.body.folderPath)); // 使用 req.body.folderPath 作为目标文件夹路径
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname);
  }
});

const upload = multer({ storage }).single('file');

// 文件上传控制器
const uploadFile = (req, res) => {
  upload(req, res, (err) => {
    if (err) {
      return res.status(500).json({ error: err.message });
    }
    res.success({ data: '文件上传成功' });
  });
};

const deleteFileOrFolder = (filePath) => {
  try {
    fs.removeSync(filePath);
    console.log(`文件或文件夹 ${filePath} 已成功删除`);
    return true;
  } catch (err) {
    console.error(err);
    return false;
  }
};
const removeFile = (sourceFilePath, recycleFilePath) => {
  // 移动文件到回收站
  console.log("🚀 ~ removeFile ~ sourceFilePath:", sourceFilePath, recycleFilePath)
  fs.move(sourceFilePath, recycleFilePath, { overwrite: false });
}
// 文件删除控制器
const deleteFile = ({ body }, res) => {
  const { directoryPath, folderName, type } = body;// 要删除的目录路径,数组字符串

  const fileNames = JSON.parse(folderName);//字符串转数组
  const deletedFiles = [];
  const failedFiles = [];

  // 循环删除文件
  fileNames.forEach((fileName) => {
    const filePath = getFilePath(directoryPath) + fileName;
    if (!fs.existsSync(filePath)) {
      failedFiles.push(fileName);
      return;
    }

    try {
      if (!type) {
        // 将文件移到recycleBin这个文件夹下面
        const recycleBinPath = path.join(__dirname, '../uploads/recycleBin/');;
        removeFile(filePath, recycleBinPath + fileName)
      } else {
        if (fs.statSync(filePath).isDirectory()) {//判断是不是文件夹
          deleteFileOrFolder(filePath) ? deletedFiles.push(fileName) : failedFiles.push(fileName);
        } else {
          fs.unlinkSync(filePath);
          deletedFiles.push(fileName);
        }
      }
    } catch (err) {
      console.error(err);
      failedFiles.push(fileName);
    }
  });



  const response = {
    message: deletedFiles.length > 0 ? '文件删除成功' : '文件或文件夹不存在',
    deletedFiles,
    failedFiles,
  };

  res.json(response);
};

const getFilePath = (folderName) => {
  const filePath = folderName ? path.join(__dirname, cloundPath + folderName) : path.join(__dirname, cloundPath)
  console.log("🚀 ~ getFilePath ~ filePath:", filePath)
  return filePath
}

const getFilesAndFolders = (dirPath) => {
  const filesList = [];
  const files = fs.readdirSync(dirPath);

  files.forEach((file) => {
    const filePath = path.join(dirPath, file);
    const stats = fs.statSync(filePath);

    if (stats.isDirectory()) {
      filesList.push({ name: file, type: 'folder', createTime: stats.birthtime });
    } else {
      filesList.push({ name: file, type: 'file', createTime: stats.birthtime });
    }
  });

  return filesList;
};

// 文件展示控制器
const getFile = async (req, res, next) => {
  const { body: { filePath, typeId }, protocol } = req
  const result = await categorizeFiles(filePath, typeId, `${protocol}://${req.get('host')}`)
  res.success({ data: result });
};
// 修改文件名称
const updateFile = async ({ body }, res) => {
  const { oldFileName, newFileName } = body;
  try {
    const oldFilePath = getFilePath(oldFileName);
    const newFilePath = getFilePath(newFileName);

    await fs.move(oldFilePath, newFilePath);

    console.log(`文件 ${oldFilePath} 已成功重命名为 ${newFilePath}`);
    res.json({ message: '文件重命名成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: '文件重命名失败' });
  }
};
// 添加文件夹
const addFolder = async ({ body }, res) => {
  const { folderName, filePath } = body
  try {
    const folderPath = getFilePath(filePath) + '/' + folderName;
    await fs.promises.mkdir(folderPath);
    console.log(`文件夹 ${folderPath}已成功创建`);
    res.success({ data: '文件夹创建成功' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: '文件夹创建失败' }
    );
  }
}
// 获取图片
const getImg = (req, res) => {
  const { filename } = req.params;
  const imagePath = getFilePath(filename);
  res.sendFile(imagePath);
}
// 将word转成markdown
const convertWordToMarkdown = async (req, res) => {
  const file = req.file; // 获取上传的文件
  if (!file) {
    return res.status(400).send('没有上传文件。');
  }
  // 使用 mammoth 将 Word 文档转换为 Markdown
  mammoth.convertToHtml({ path: file.path })
    .then(result => {
      // 删除上传的文件
      fs.unlinkSync(file.path);
      // 设置响应头为 HTML
      res.setHeader('Content-Type', 'text/html');
      // 发送转换后的 Markdown 文本
      res.send(`<!DOCTYPE html>
      <html lang="en-US">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, user-scalable=no">
        <title>Sekonda Smart - Privacy Policy</title>
      </head>
      <body>
      ${result.value}
      </body>
      </html>`);
    })
    .catch(err => {
      // 发生错误时，删除上传的文件
      fs.unlinkSync(file.path);
      // 发送错误响应
      res.status(500).send('文件转换失败。');
    });
}
// 分享列表
const share = async (req, res) => {
  // 根据userId获取mysql的数据库表中分享记录
  const { userId } = req.params;
  const result = await Share.find({ userId });
  if (result) {
    res.success({ data: result });
  } else {
    res.status(404).json({ message: '没有找到分享记录' });
  }
}
module.exports = { uploadFile, deleteFile, getFile, updateFile, addFolder, getImg, convertWordToMarkdown, upload, share };